const socketio = {};  
const { Server } = require('socket.io');
const {Chat}  = require('../model/chat') 
const {User} = require('../model/user')
const moment= require('moment-timezone')
//获取io  
socketio.getSocketio = function(server){  
    let io = new Server(server, { cors: true });
    io.sockets.on('connection', (socket) => {
        socket.on('sendMsg',async (data) => {
            // console.log(data)
            const chat = new Chat(
                {
                    ...data,
                 dateTime: moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss')
                })
            // console.log(chat)
            await chat.save()
            let chatOne =await Chat.findById(chat._id).populate({
                path:"from to",
                populate:{
                    path:"avatar",
                    strictPopulate:false
                }
            })
            //发回chatone
            io.emit('pushMsg', chatOne)
            io.emit('toMsg',chatOne)
        })
        socket.on("sendContact",async(data)=>{
            if(!data) {
                io.emit('pushError', "连接失败")
            }
            const {user,contact} = data
            if(user!=contact){
                let loginUserContact = await User.findById(user).select("+chatContact")
                if(!loginUserContact.chatContact.includes(contact)){
                    const loginUser =await User.findByIdAndUpdate(user,{$push:{
                        chatContact:contact
                    }}).select('+chatContact')
                    await User.findByIdAndUpdate(contact,{$push:{
                        chatContact:user
                    }}).select('+chatContact')
                    if(!loginUser) {
                        io.emit('pushError', "添加联系人失败")
                    }
                } else {
                    io.emit('pushError', "不能给自己发私信")
                }
            }
        })
        socket.on("getVote",async(data)=>{
            if(!data) {
                io.emit('pushError', "连接失败")
            }

        })
    });
};  

module.exports = socketio;  